﻿@{
	PageData["Title"] = "Forgot Password";

	var db = Database.Open("wishlistdb");
}

<h1>Forgot Password</h1>
@if (IsPost) {
    var username = Request["username"];
    var userEmail = "";
    var errorMessage = "";
    //Get user's e-mail
    if (!username.IsEmpty()) {
        var user = db.QuerySingle("SELECT Email FROM WishlistUser WHERE Username = @0", username);
        if (user != null) {
            userEmail = user.Email;
        }
    }
    //Generate reset token and send e-mail to the user
    if (!userEmail.IsEmpty()) {
        if (WebSecurity.IsConfirmed(username)) {
            var resetToken = WebSecurity.GeneratePasswordResetToken(username, 60);
            var serverUri = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
            var body = "Please click <a href=\"" + serverUri + VirtualPathUtility.ToAbsolute("~/account/passwordreset?resetCode=") +
                    HttpUtility.UrlEncode(resetToken) + "\">this link</a> to reset your password.";
			// If email not configured, then display confirmation link on the web page
			if (WebMail.UserName.IsEmpty() || WebMail.Password.IsEmpty() || WebMail.From.IsEmpty()) {
			    // No email sent, forward to link display page
			    Response.Redirect("~/Shared/Setup/MailSetupReset?resetCode="+ HttpUtility.UrlEncode(resetToken));
			} else {
				try {
						WebMail.Send(to: userEmail, subject: "Password Reset", body: body);
					} catch (Exception) {
						Response.Redirect("~/Shared/Errors/MailError");
					}
					Response.Redirect("~/Shared/Success/SentMailSuccess");
			 }
        } else {
            errorMessage = "<li>Your account has not yet been confirmed!  Check your e-mail.</li>";
        }
    } else {
        errorMessage = "<li>Your username was not found in our system.</li>";
    }
    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}
<div>
    Forgot your password?  Enter your username and we will send you reset instructions via e-mail.
    <form id="validateForm" method="post" action="">
	    <fieldset>
		    @RenderPage("~/Shared/_InputFormField.cshtml",
                new {labelName = "username", labelDisplay = "Username:", maxLength = 30, required = true})
		    <div class="submit-group">
			    <input type="submit" value="Send Mail" onclick="javascript:$('#validateForm').validate()" />
		    </div>
	    </fieldset>
    </form>
</div>
